<?php

namespace app\admin\controller\manager;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use app\common\model\Recharge as RechargeModel;
use app\admin\model\Admin;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Recharge extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model            = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'recharge_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new RechargeModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //
            $join[] = ["admin a", "a.id = re.admin_id"];
            $join[] = ["auth_group_access ac", "a.id = ac.uid"];
            $join[] = ["auth_group g", "g.id = ac.group_id"];
            //$join[] = ["file f", "f.id = re.file_id"];
            $join[] = ['shop_admin_wallet w', 'w.admin_id = a.id'];
            $field  = "re.recharge_id as id,a.username,a.nickname,a.status,a.role,g.pid,g.name,re.recharge_image,re.status as recharge_status,re.recharge_money,w.balance";
            $total  = $this->model->alias('re')->join($join)->field($field)->where($where)->count();
            $list   = $this->model->alias('re')->join($join)->field($field)->where($where)->limit($offset, $limit)->select();
            //dump($this->model->getLastSql());
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $key => $value) {
                if ($value['role'] == 1) {
                    $list[$key]['group'] = '管理员';
                }
                if ($value['role'] == 2) {
                    $list[$key]['group'] = '普通用户';
                }
                $list[$key]['platform'] = $value['name'];
                if($value['recharge_status'] == 0){
                    $list[$key]['recharge_status'] = '待充值';
                }else{
                    $list[$key]['recharge_status'] = '已充值';
                }
                if($value['status'] == 'normal'){
                    $list[$key]['status'] = '正常';
                }else{
                    $list[$key]['status'] = '禁用';
                }
                $value['fullurl'] = $this->view->config['upload']['cdnurl'] . $value['recharge_image'];
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function change_balance($ids = '')
    {
        $row = $this->model->get(['recharge_id' => $ids]);
        $row['username'] = Admin::where('id', $row['admin_id'])->value('username');
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($row->status == 1){
                $this->error('该笔充值已完成，请勿重复提交');
            }
            \think\Db::startTrans();
            try {
                $params['ad_username'] = session('admin')['username'];
                //halt($params);
                $result = $this->model->save($params,['recharge_id'=>$ids]);
                //echo $result;exit;
                $wallet = Db::name('shop_admin_wallet')->where('admin_id', $row->admin_id)->find();
                if($wallet){
                    $re = Db::name('shop_admin_wallet')->where('admin_id', $row->admin_id)->setInc('balance', $params['recharge_money']);
                }else{
                    $re = Db::name('shop_admin_wallet')->where('admin_id',$row->id)->update([ 'balance' => $params['recharge_money']]);
                }
                if($re !== false && $result !== false){
                    \think\Db::commit();
                    $this->success();

                }else{
                    \think\Db::rollback();
                    $this->error();
                }
            } catch (Exception $e) {
                think\Db::rollback();
                $this->error();
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
